package net.jsoft.platform.schedule.util;

import java.util.Date;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.SimpleTrigger;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.quartz.impl.StdSchedulerFactory;

import net.jsoft.platform.schedule.job.BaseJob;

public class ScheduleUtils
{
    public static String TRIGGER_GROUP_NAME = "TRIGGER_GROUP_NAME";

    public static void addJob(String jobName, String jobClassName, String cronExpression, String jobDescription, String ip, String port) throws Exception
    {

        // 通过SchedulerFactory获取一个调度器实例  
        //        SchedulerFactory sf = StdSchedulerFactory.getDefaultScheduler() ;//new StdSchedulerFactory();

        Scheduler sched = StdSchedulerFactory.getDefaultScheduler();

        // 启动调度器  
        sched.start();

        //构建job信息
        JobDetail jobDetail = JobBuilder.newJob(getClass(jobClassName).getClass()).withIdentity(jobName, TRIGGER_GROUP_NAME).withDescription(jobDescription).build();

        //表达式调度构建器(即任务执行的时间)
        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression);

        //按新的cronExpression表达式构建一个新的trigger
        CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(jobName, TRIGGER_GROUP_NAME).withSchedule(scheduleBuilder).withDescription(jobDescription).build();

        try
        {
            if (StringUtils.isNotEmpty(port))
            {
                jobDetail.getJobDataMap().put("port", port);
            }
            if (StringUtils.isNotEmpty(ip))
            {
                jobDetail.getJobDataMap().put("ip", ip);
            }

            sched.scheduleJob(jobDetail, trigger);

        }
        catch (SchedulerException e)
        {
            System.out.println("创建定时任务失败" + e);
            throw new Exception("创建定时任务失败");
        }
    }

    public static void jobPause(String jobName) throws Exception
    {
        // 通过SchedulerFactory获取一个调度器实例  
        //        SchedulerFactory sf = new StdSchedulerFactory();
        Scheduler sched = StdSchedulerFactory.getDefaultScheduler();
        //        Scheduler sched = sf.getScheduler();
        sched.pauseJob(JobKey.jobKey(jobName, TRIGGER_GROUP_NAME));
    }

    public static JobDetail getJobDetail(String jobName) throws Exception
    {
        // 通过SchedulerFactory获取一个调度器实例  
        //        SchedulerFactory sf = new StdSchedulerFactory();
        //        Scheduler sched = sf.getScheduler();
        Scheduler sched = StdSchedulerFactory.getDefaultScheduler();
        return sched.getJobDetail(JobKey.jobKey(jobName, TRIGGER_GROUP_NAME));
    }

    public static void jobresume(String jobName) throws Exception
    {
        // 通过SchedulerFactory获取一个调度器实例  
        SchedulerFactory sf = new StdSchedulerFactory();
        Scheduler sched = sf.getScheduler();
        sched.resumeJob(JobKey.jobKey(jobName, TRIGGER_GROUP_NAME));
    }

    public static void jobreschedule(String jobName, String cronExpression) throws Exception
    {
        try
        {
            //            SchedulerFactory schedulerFactory = new StdSchedulerFactory();
            //            Scheduler scheduler = schedulerFactory.getScheduler();
            Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
            TriggerKey triggerKey = TriggerKey.triggerKey(jobName, TRIGGER_GROUP_NAME);
            // 表达式调度构建器
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression);

            CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);

            // 按新的cronExpression表达式重新构建trigger
            trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();

            // 按新的trigger重新设置job执行
            scheduler.rescheduleJob(triggerKey, trigger);
        }
        catch (SchedulerException e)
        {
            System.out.println("更新定时任务失败" + e);
            throw new Exception("更新定时任务失败");
        }
    }

    public static void jobUpdateSchedule(String jobName, String jobClassName, String cronExpression, String remark, String ip, String port) throws Exception
    {
        try
        {
            //            SchedulerFactory schedulerFactory = new StdSchedulerFactory();
            //            Scheduler scheduler = schedulerFactory.getScheduler();
            Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
            JobKey jk = JobKey.jobKey(jobName, TRIGGER_GROUP_NAME);
            scheduler.pauseTrigger(TriggerKey.triggerKey(jobName, TRIGGER_GROUP_NAME));
            scheduler.unscheduleJob(TriggerKey.triggerKey(jobName, TRIGGER_GROUP_NAME));
            scheduler.deleteJob(jk);
            //构建job信息
            JobDetail jobDetail = JobBuilder.newJob(getClass(jobClassName).getClass()).withIdentity(jobName, TRIGGER_GROUP_NAME).build();
            if (StringUtils.isNotEmpty(port))
            {
                jobDetail.getJobDataMap().put("port", port);
            }
            if (StringUtils.isNotEmpty(ip))
            {
                jobDetail.getJobDataMap().put("ip", ip);
            }
            //表达式调度构建器(即任务执行的时间)
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression);
            //按新的cronExpression表达式构建一个新的trigger
            CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(jobName, TRIGGER_GROUP_NAME).withSchedule(scheduleBuilder).withDescription(remark).build();
            // 按新的trigger重新设置job执行
            scheduler.scheduleJob(jobDetail, trigger);
        }
        catch (SchedulerException e)
        {
            System.out.println("更新定时任务失败" + e);
            throw new Exception("更新定时任务失败");
        }
    }

    public static void jobdelete(String jobName) throws Exception
    {
        // 通过SchedulerFactory获取一个调度器实例  
        //        SchedulerFactory sf = new StdSchedulerFactory();
        //        Scheduler sched = sf.getScheduler();
        Scheduler sched = StdSchedulerFactory.getDefaultScheduler();
        sched.pauseTrigger(TriggerKey.triggerKey(jobName, TRIGGER_GROUP_NAME));
        sched.unscheduleJob(TriggerKey.triggerKey(jobName, TRIGGER_GROUP_NAME));
        sched.deleteJob(JobKey.jobKey(jobName, TRIGGER_GROUP_NAME));
    }

    public static void doOnce(String jobName) throws Exception
    {
        // 通过SchedulerFactory获取一个调度器实例  
        //        SchedulerFactory sf = new StdSchedulerFactory();
        //        Scheduler sched = sf.getScheduler();
        Scheduler sched = StdSchedulerFactory.getDefaultScheduler();

        JobDetail tjd = getJobDetail(jobName);
        String jn = jobName + UUID.randomUUID().toString();

        JobDetail job = JobBuilder.newJob(tjd.getJobClass()).withIdentity(jn, TRIGGER_GROUP_NAME).withDescription(tjd.getDescription()).setJobData(tjd.getJobDataMap()).build();

        SimpleTrigger simpleTrigger = TriggerBuilder.newTrigger().withIdentity(jn, TRIGGER_GROUP_NAME).startAt(new Date())
                .withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(3).withRepeatCount(0))//重复执行的次数，因为加入任务的时候马上执行了，所以不需要重复，否则会多一次。  
                .build();
        sched.scheduleJob(job, simpleTrigger);

    }

    public static BaseJob getClass(String classname) throws Exception
    {
        Class<?> class1 = Class.forName(classname);
        return (BaseJob) class1.newInstance();
    }
}
